package com.aeon.profiler;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import com.aeon.asm.PerfClassAdapter;

public class Transformer implements ClassFileTransformer {

	private String mKey;

	public Transformer(String key1, Instrumentation inst) {
		mKey = key1;
	}

	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {

		return transform0(loader, className, classfileBuffer);
	}

	private byte[] transform0(ClassLoader loader, String className,
			byte[] classfileBuffer) {
		if (!className.contains(mKey)||className.contains("log")||className.contains("registry")) {
			return classfileBuffer;
		}
//		if(loader!=null){
//			try {
//				loader.loadClass(TimeProfile.class.getName());
//			} catch (ClassNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}

		byte[] result = classfileBuffer;
		ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
		ClassVisitor adapter = new PerfClassAdapter(writer, className);
		ClassReader reader = new ClassReader(classfileBuffer);
		reader.accept(adapter, 0);
		result = writer.toByteArray();
		return result;
	}
}